<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\common\controller\AdminController;
use app\common\utils\JsonResponse;
use think\App;
use app\admin\validate\AdminValidate;
use think\facade\Request;
use app\common\model\Admin as AdminModel;
use think\facade\Db;
use app\common\model\AdminRole as AdminRoleModel;

class Admin extends AdminController
{

    protected AdminModel $adminModel;
    protected AdminRoleModel $adminRoleModel;
    /**
     * 构造方法
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->adminModel = new AdminModel();
        $this->adminRoleModel = new AdminRoleModel();
    }
    
    /**
     * 获取管理员列表
     * @permission system:admin:query
     */
    public function getList()
    {
        $params = Request::get();
        
        try {
            // 标准化分页参数
            $pageNo = isset($params['pageNo']) ? intval($params['pageNo']) : 1;
            $pageSize = isset($params['pageSize']) ? intval($params['pageSize']) : 10;
            
            // 查询条件
            $where = [];
            if (!empty($params['nickname'])) {
                $where[] = ['nickname', 'like', "%{$params['nickname']}%"];
            }
            if (isset($params['status']) && $params['status'] !== '') {
                $where[] = ['status', '=', intval($params['status'])];
            }
            
            // 查询列表
            $list = $this->adminModel->with(['roles'])
                ->where($where)
                ->field('admin_id,username,nickname,avatar,status,last_login_time,last_login_ip,create_time,update_time')
                ->order('admin_id', 'asc')
                ->paginate([
                    'list_rows' => $pageSize,
                    'page' => $pageNo
                ])
                ->each(function($item) {
                    $item['role_ids'] = array_column($item['roles']->toArray(), 'id');
                    return $item;
                });
                
            return JsonResponse::successPaginate($list);
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }
    
    /**
     * 添加管理员
     * @permission system:admin:doAdd
     */
    public function doAdd()
    {
        $params = Request::post();
        
        try {
            validate(AdminValidate::class)
                ->scene('add')
                ->check($params);
                
            // 检查用户名是否存在
            if ($this->adminModel->where('username', $params['username'])->find()) {
                return JsonResponse::error('用户名已存在');
            }
            
            // 开启事务
            Db::startTrans();
            try {
                // 生成密码盐
                $salt = substr(md5(uniqid()), 0, 6);
                // 加密密码
                $password = md5($params['password'] . $salt);
                
                $data = [
                    'username' => $params['username'],
                    'password' => $password,
                    'salt' => $salt,
                    'nickname' => $params['nickname'] ?? $params['username'],
                    'avatar' => $params['avatar'] ?? '',
                    'status' => $params['status'] ?? 1,
                ];
                
                // 保存管理员信息
                if (!$this->adminModel->save($data)) {
                    throw new \Exception('添加管理员失败');
                }
                
                // 保存角色关联
                if (!empty($params['role_ids'])) {
                    if (!$this->adminRoleModel->saveAdminRoles($this->adminModel->admin_id, $params['role_ids'])) {
                        throw new \Exception('保存角色关联失败');
                    }
                }
                
                Db::commit();
                return JsonResponse::success([], '添加成功');
                
            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }
            
        } catch (\think\exception\ValidateException $e) {
            return JsonResponse::error($e->getMessage());
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }
    
    /**
     * 修改管理员
     * @permission system:admin:doEdit
     */
    public function doEdit()
    {
        $params = Request::post();
        
        try {
            validate(AdminValidate::class)
                ->scene('edit')
                ->check($params);
                
            $admin = $this->adminModel->find($params['admin_id']);
            if (!$admin) {
                return JsonResponse::error('管理员不存在');
            }
            
            // 检查用户名是否被其他人使用
            if ($this->adminModel->where('username', $params['username'])
                ->where('admin_id', '<>', $params['admin_id'])
                ->find()) {
                return JsonResponse::error('用户名已存在');
            }
            
            // 开启事务
            Db::startTrans();
            try {
                $data = [
                    'username' => $params['username'],
                    'nickname' => $params['nickname'] ?? $params['username'],
                    'avatar' => $params['avatar'] ?? '',
                    'status' => $params['status'] ?? 1
                ];
                
                // 如果修改密码
                if (!empty($params['password'])) {
                    $salt = substr(md5(uniqid()), 0, 6);
                    $data['password'] = md5($params['password'] . $salt);
                    $data['salt'] = $salt;
                }
                
                // 更新管理员信息
                if (!$admin->save($data)) {
                    throw new \Exception('修改管理员失败');
                }
                
                // 更新角色关联
                if (isset($params['role_ids'])) {
                    if (!$this->adminRoleModel->saveAdminRoles($params['admin_id'], $params['role_ids'])) {
                        throw new \Exception('更新角色关联失败');
                    }
                }
                
                Db::commit();
                return JsonResponse::success([], '修改成功');
                
            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }
            
        } catch (\think\exception\ValidateException $e) {
            return JsonResponse::error($e->getMessage());
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }
    
    /**
     * 删除管理员
     * @permission system:admin:doDelete
     */
    public function doDelete()
    {
        $params = Request::post();
        
        try {
            if ($params['admin_id'] == 1) {
                return JsonResponse::error('超级管理员不能删除');
            }
            
            $admin = $this->adminModel->find($params['admin_id']);
            if (!$admin) {
                return JsonResponse::error('管理员不存在');
            }
            
            if ($admin->delete()) {
                return JsonResponse::success([], '删除成功');
            }
            return JsonResponse::error('删除失败');
            
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }
} 